package com.zwr.sheller.shop.controller;

import com.github.pagehelper.PageInfo;
import com.zwr.sheller.core.common.JsonResult;
import com.zwr.sheller.shop.service.SalesDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * 销售数据
 * @author 付龙江
 * @date 2022/1/6 9:25
 */
@CrossOrigin
@RestController
@RequestMapping("/salesData")
@Api(tags = "后台首页/销售数据统计接口")
public class SalesDataController {

    @Autowired
    SalesDataService salesDataService;

    /**
     *
     * @return 订单走势图/成交单数相关数据
     */
    @PostMapping("/orderCount")
    @ApiOperation(value = "订单走势图/成交单数")
    public Map<String,Object> orderCount(){
        return salesDataService.selectOrderCount();
    }


    /**
     * 订单统计下具体订单
     * @param from 开始时间
     * @param to 截止时间
     * @param page 页数
     * @param size 每页条数
     * @return 返回对应信息
     */
    @PostMapping("/specificOrder")
    @ApiOperation(value = "订单统计下面具体订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "Integer", paramType = "query")
    })
    public Map<String,Object> specificOrder(String from, String to, Integer page , Integer size){
        PageInfo<Map<String, Object>> mapPageInfo = salesDataService.selectSpecificOrder(from, to, page, size);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setField("total",mapPageInfo.getTotal());
        jsonResult.setField("data",mapPageInfo.getList());
        return jsonResult.getMap();
    }
    @PostMapping("/uploadSpecificOrder")
    @ApiOperation(value = "导出订单统计下面具体订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query")
    })
    public void uploadSpecificOrder(HttpServletResponse response, String from,String to)throws IOException{
        List<Map<String, Object>> list1 = salesDataService.uploadSpecificOrder(from, to);
        //导出
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("订单统计表");
        String fileName="订单统计表"+".xls";
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        String[] headers = {"订单编号", "总成交金额", "下单时间"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (Map<String, Object> map : list1) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(map.get("orderNum").toString());
            dataRow.createCell(1).setCellValue(map.get("totalMoney").toString());
            dataRow.createCell(2).setCellValue(map.get("createTime").toString());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());


    }



    @PostMapping("/salesCount")
    @ApiOperation(value = "销售统计表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "Integer", paramType = "query")
    })
    public Map<String,Object> salesCount(String from, String to, Integer page , Integer size){
        return salesDataService.selectSalesData(from, to, page, size);
    }

    @PostMapping("/uploadSalesCount")
    @ApiOperation(value = "导出销售统计表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query")
    })
    public void uploadSalesCount(HttpServletResponse response, String from,String to) throws IOException {
        //拿到要导出的信息
        List<Map<String, Object>> list1 = salesDataService.uploadSalesData(from, to);
        //导出
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("销售统计表");
        String fileName="销售统计表"+".xls";
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        String[] headers = {"日期", "总生产订单", "总成交订单", "总成交金额"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (Map<String, Object> map : list1) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(map.get("dayTime").toString());
            dataRow.createCell(1).setCellValue(map.get("allOrder").toString());
            dataRow.createCell(2).setCellValue(map.get("successOrder").toString());
            dataRow.createCell(3).setCellValue(map.get("totalMoney").toString());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }



    @PostMapping("/salesDetail")
    @ApiOperation(value = "销售明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "notPayStatus", value = "待付款（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "deliverGoodsStatus", value = "待发货（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "getGoodsStatus", value = "待收货（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "backGoodsStatus", value = "退货中（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "cancelStatus", value = "已取消（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "successStatus", value = "已完成（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "usToOrderStatus", value = "自提订单（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query")
    })
    public Map<String,Object> salesDetail(String from, String to, Integer page , Integer size,
                                          Integer notPayStatus, Integer deliverGoodsStatus,
                                          Integer getGoodsStatus, Integer backGoodsStatus,
                                          Integer cancelStatus, Integer successStatus,
                                          Integer usToOrderStatus){
        PageInfo<Map<String, Object>> mapPageInfo = salesDataService.selectSalesDetail(from, to, page, size, notPayStatus, deliverGoodsStatus, getGoodsStatus, backGoodsStatus, cancelStatus, successStatus, usToOrderStatus);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setField("total",mapPageInfo.getTotal());
        jsonResult.setField("data",mapPageInfo.getList());
        return jsonResult.getMap();
    }

    @PostMapping("/uploadSalesDetail")
    @ApiOperation(value = "导出销售明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "notPayStatus", value = "待付款（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "deliverGoodsStatus", value = "待发货（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "getGoodsStatus", value = "待收货（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "backGoodsStatus", value = "退货中（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "cancelStatus", value = "已取消（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "successStatus", value = "已完成（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "usToOrderStatus", value = "自提订单（1是选中  0或null是没有选）", required = false, dataType = "Integer", paramType = "query")
    })
    public void uploadSalesDetail(HttpServletResponse response,String from, String to,
                                  Integer notPayStatus, Integer deliverGoodsStatus,
                                  Integer getGoodsStatus, Integer backGoodsStatus,
                                  Integer cancelStatus, Integer successStatus,
                                  Integer usToOrderStatus)throws IOException{
        List<Map<String, Object>> list1 = salesDataService.uploadSalesDetail(from, to, notPayStatus, deliverGoodsStatus, getGoodsStatus, backGoodsStatus, cancelStatus, successStatus, usToOrderStatus);
        //导出
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("销售明细表");
        String fileName="销售明细表"+".xls";
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        String[] headers = {"商品编号", "商品名称", "商品类型","商品主图","订单号","店家名称","数量","单价","出售金额","下单时间"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (Map<String, Object> map : list1) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(map.get("goodsId").toString());
            dataRow.createCell(1).setCellValue(map.get("goodsName").toString());
            dataRow.createCell(2).setCellValue(map.get("itemName").toString());
            dataRow.createCell(3).setCellValue(map.get("goodsMainImg").toString());
            dataRow.createCell(4).setCellValue(map.get("orderNum").toString());
            dataRow.createCell(5).setCellValue(map.get("userRetailName").toString());
            dataRow.createCell(6).setCellValue(map.get("num").toString());
            dataRow.createCell(7).setCellValue(map.get("avgPrice").toString());
            dataRow.createCell(8).setCellValue(map.get("totalMoney").toString());
            dataRow.createCell(9).setCellValue(map.get("createTime").toString());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }


    @PostMapping("/salesRanking")
    @ApiOperation(value = "销售排行")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "rule", value = "排名规则(1：成交量由高到底，2：成交量由底到高，3：成交金额由高到低，4：成交金额由低到高)", required = false, dataType = "Integer", paramType = "query")
    })
    public Map<String,Object> salesRanking(Integer rule, String from, String to, Integer page , Integer size){
        JsonResult jsonResult = new JsonResult();
        PageInfo<Map<String, Object>> mapPageInfo = salesDataService.selectSalesRanking(from, to, page, size, rule);
        jsonResult.setField("data",mapPageInfo.getList());
        jsonResult.setField("total",mapPageInfo.getTotal());
        return jsonResult.getMap();
    }

    @PostMapping("/uploadSalesRanking")
    @ApiOperation(value = "导出销售排行")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "to", value = "截止时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "rule", value = "排名规则(1：成交量由高到底，2：成交量由底到高，3：成交金额由高到低，4：成交金额由低到高)", required = false, dataType = "Integer", paramType = "query")
    })
    public void uploadSalesRanking(HttpServletResponse response,Integer rule, String from, String to) throws IOException{
        List<Map<String, Object>> list1 = salesDataService.uploadSalesRanking(from, to, rule);
        //导出
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("销售排行表");
        String fileName="销售排行表"+".xls";
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        String[] headers = {"排名","商品编号", "商品名称", "商品类型","商品主图","数量","成交金额","均价"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        int rowNum = 1;
        for (Map<String, Object> map : list1) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(map.get("rank").toString());
            dataRow.createCell(1).setCellValue(map.get("goodsId").toString());
            dataRow.createCell(2).setCellValue(map.get("goodsName").toString());
            dataRow.createCell(4).setCellValue(map.get("itemName").toString());
            dataRow.createCell(5).setCellValue(map.get("goodsMainImg").toString());
            dataRow.createCell(6).setCellValue(map.get("num").toString());
            dataRow.createCell(7).setCellValue(map.get("totalMoney").toString());
            dataRow.createCell(8).setCellValue(map.get("avgPrice").toString());
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream");
        //附件格式打卡，不是打开页面
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }



    @PostMapping("/moneyDetail")
    @ApiOperation(value = "资金明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "clearing", value = "结算方式", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "paymentType", value = "收支类型", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "detailType", value = "明细类型", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "createTime", value = "创建时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "Integer", paramType = "query")
    })
    public Map<String,Object> moneyDetail(Integer clearing, Integer paymentType, Integer detailType, String createTime, Integer page , Integer size){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setField("data",null);
        return jsonResult.getMap();
    }

    @PostMapping("/cashDetail")
    @ApiOperation(value = "贴现明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "createTime", value = "创建时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, dataType = "Integer", paramType = "query")
    })
    public Map<String,Object> cashDetail(Integer status, String createTime, Integer page, Integer size){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setField("data",null);
        return jsonResult.getMap();
    }


    @PostMapping("/indexInfo")
    @ApiOperation(value = "首页信息")
    public Map<String, Object> indexInfo(){
        return salesDataService.selectIndexMessage();
    }
}
